export class ApiCache<T = any> {
  private cache = new Map<string, { data: T; expireAt: number }>();
  private defaultTTL: number;

  constructor(defaultTTL = 60000) {
    this.defaultTTL = defaultTTL;
  }

  private now() {
    return Date.now();
  }

  set(key: string, data: T, ttl = this.defaultTTL): void {
    const expireAt = this.now() + ttl;
    this.cache.set(key, { data, expireAt });
  }

  get(key: string): T | null {
    const entry = this.cache.get(key);
    if (!entry) return null;
    if (this.now() > entry.expireAt) {
      this.cache.delete(key);
      return null;
    }
    return entry.data;
  }

  async fetch(key: string, fetchFn: () => Promise<T>, ttl = this.defaultTTL): Promise<T> {
    const cached = this.get(key);
    if (cached) return cached;

    const data = await fetchFn();
    this.set(key, data, ttl);
    return data;
  }

  clear(key?: string): void {
    if (key) {
      this.cache.delete(key);
    } else {
      this.cache.clear();
    }
  }
}
